﻿using Less.Html;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ByteSite.Web
{
    public partial class caiji : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnCatch_Click(object sender, EventArgs e)
        {

            //https://yx.3.cn/service/info.action?ids=385823  小参数
            //https://c.3.cn/recommend?methods=accessories&sku=385823&cat=670,729,4837 参数
            //https://pe.3.cn/prices/mgets?skuids=385823 价格
            //https://cd.jd.com/description/channel?skuId=385823&mainSkuId=385823  详情
            //https://club.jd.com/comment/productPageComments.action?productId=5463695&score=0&sortType=5&page=0&pageSize=10  评价

            //https://img14.360buyimg.com/n0/jfs/t1/80662/31/15678/168779/5dd33225E2f664613/bc9626a74965e933.jpg

            string url = txtUrls.Text;
            string jdId = url.ToLower().Replace("https://item.jd.com/", "");
            jdId = jdId.Substring(0, jdId.IndexOf(".html"));

            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; //加上这一句
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://item.jd.com/" + jdId + ".html");
            request.Method = "GET";
            request.Headers.Add("DNT", "1");
            //request.ContentType = "application/x-www-form-urlencoded";
            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9";
            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36";

            request.Timeout = 15000;
            request.AllowAutoRedirect = false;

            WebResponse response = null;
            string responseStr = null;

            try
            {
                response = request.GetResponse();

                if (response != null)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    responseStr = reader.ReadToEnd();
                    reader.Close();
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                request = null;
                response = null;
            }

            txtResult.Text = responseStr;
            
            Entitys.CloudGoods cloudGoods = new Entitys.CloudGoods();

            //正则解析
            Regex regCat = new Regex(@"cat:.*]", RegexOptions.IgnoreCase);
            Match catMatch = regCat.Match(responseStr);
            string catStr = string.Empty;
            if (catMatch.Success)
            {
                //获取京东类别
                catStr = catMatch.Value.Remove(0,catMatch.Value.IndexOf("[")).TrimStart('[').TrimEnd(']');
            }

            //解析html
            var html = HtmlParser.Query(responseStr, false);
            var specHtml = html("#spec-list ul li");
            int i = 0;
            foreach (Element ele in specHtml)
            {
                var specLiHtml = HtmlParser.Query(ele.innerHTML, false);
                var img = specLiHtml("img");
                if (img.length > 0)
                {
                    i++;
                    cloudGoods.Images = new List<Entitys.CloudGoodsImages>();
                    cloudGoods.Images.Add(new Entitys.CloudGoodsImages { Order = i, Remark = "", Url = "https://img14.360buyimg.com/n0/" + img[0].getAttribute("data-url") });
                }
            }
            //抓取接口

            //抓取产品参数
            request = (HttpWebRequest)HttpWebRequest.Create("https://c.3.cn/recommend?methods=accessories&sku=" + jdId + "&cat=" + catStr);
            request.Method = "GET";
            request.Headers.Add("DNT", "1");
            //request.ContentType = "application/x-www-form-urlencoded";
            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9";
            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36";

            request.Timeout = 15000;
            request.AllowAutoRedirect = false;

            response = null;
            responseStr = null;

            try
            {
                response = request.GetResponse();

                if (response != null)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    responseStr = reader.ReadToEnd();
                    reader.Close();
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                request = null;
                response = null;
            }
            txtResult.Text = responseStr;

        }
    }
}